import './index.less';
import { useSize } from 'ahooks';
import { Fragment } from 'react';

export default function MyForm({ form, formsColumn = [], query = false, collapsed = true, searchFn, resetFn, children, ...$attrs }) {
	// 展开、收起
	const [currentCollapsed, setCurrentCollapsed] = useState(collapsed);

	// 监听dom元素宽高变化
	const refMyForm = useRef(null),
		refMyFormQuery = useRef(null),
		MyFormSize = useSize(refMyForm),
		MyFormQuerySize = useSize(refMyFormQuery);

	const [currentColumn, setCurrentColumn] = useState(4);

	// 生成组件
	function formsItem(row) {
		if (MyFormSize) {
			const width = MyFormSize.width;
			if (width <= 700) {
				setCurrentColumn(2);
			} else if (width >= 700 && width <= 1171) {
				setCurrentColumn(3);
			} else if (width >= 1172 && width <= 1379) {
				setCurrentColumn(4);
			} else if (width >= 1380 && width <= 1779) {
				setCurrentColumn(5);
			} else if (width >= 1780) {
				setCurrentColumn(6);
			}
		}

		let itemWidth;
		if (MyFormQuerySize) itemWidth = `calc(${100 / currentColumn}% - ${MyFormQuerySize.width / currentColumn}px)`;

		// 过滤出显示的数据
		const formsColumnList = formsColumn.filter(({ show = true }) => show);

		return formsColumnList.map(({ itemType = 'input', col = {}, required, name, label, rules, FormItem, ...props }, index) => {
			// 默认验证规则
			if (required && !rules) {
				rules = [
					{
						required: true,
						message: `${label}不能为空`
					}
				];
			}

			// 默认placeholder提示
			if (['tree', 'cascader', 'select'].includes(itemType)) {
				props.placeholder = `请选择${label}`;
			} else {
				itemType !== 'date' && (props.placeholder = `请输入${label}`);
			}

			// 组件对应表
			const Comp = new Map([
				['tree', TreeSelect],
				['switch', Switch],
				['checkbox', Checkbox.Group],
				['radio', Radio.Group],
				['cascader', MyCascader],
				['select', MySelect],
				['number', MyInputNumber],
				['date', MyDatePicker],
				['input', MyInput]
				// ['file', MyFileUpload],
				// ['img', MyImgUpload],
			]).get(itemType);

			// checked 选中值
			if (itemType.includes(['switch'])) FormItem.valuePropName = 'checked';

			// FormItem 组件内容
			let itemData = (
				<div
					key={name}
					style={{ width: itemWidth, ...vShow(!query || (query && (index < currentColumn || !currentCollapsed))).style }}
					className="mb-10"
				>
					<Form.Item name={name} label={label} rules={rules} {...FormItem}>
						{$attrs[name] ? $attrs[name] : <Comp {...props} />}
					</Form.Item>
				</div>
			);

			// 是否栅格布局
			if (row)
				itemData = (
					<Col {...col} key={'Col' + index}>
						{itemData}
					</Col>
				);

			// 添加查询按钮
			if (
				query &&
				((index === currentColumn - 1 && formsColumnList.length > currentColumn) ||
					(formsColumnList.length <= currentColumn && index === formsColumnList.length - 1))
			) {
				itemData = (
					<Fragment key={'MyFormQuery_' + index}>
						{itemData}
						<Form.Item className="MyFormQuery">
							<div ref={refMyFormQuery}>
								{children ? (
									children
								) : (
									<>
										<Button type="primary" onClick={searchFn} className="mr-10">
											<MyIcon icon="SearchOutlined" />
											搜索
										</Button>
										<Button onClick={resetFn}>
											<MyIcon icon="SyncOutlined" />
											重置
										</Button>
										{formsColumn.length > currentColumn && (
											<Button type="link" onClick={() => setCurrentCollapsed(!currentCollapsed)}>
												{currentCollapsed ? '展开' : '收起'}
												<MyIcon icon={currentCollapsed ? 'CaretDownOutlined' : 'CaretUpOutlined'} />
											</Button>
										)}
									</>
								)}
							</div>
						</Form.Item>
					</Fragment>
				);
			}
			return itemData;
		});
	}
	return (
		<div ref={refMyForm} className="MyForm">
			<Form form={form} layout="inline" {...$attrs}>
				{useMemo(
					() => ($attrs.row ? <Row {...$attrs.row}>{formsItem(true)}</Row> : formsItem(false)),
					[formsColumn, currentCollapsed, MyFormSize, MyFormQuerySize]
				)}
			</Form>
		</div>
	);
}

/***
 * 参数属性
 * @property {Array} formsColumn 生成form表单的配置数组
 * @property {Boolean} query 是否默认添加查询 重置按钮
 * @property {Boolean} [collapsed=true] 初始收起表单项目，collapsible=true是才有效
 * @property {Function} [searchFn] 查询函数
 */
MyForm.propTypes = {
	formsColumn: propTypes.array.isRequired,
	query: propTypes.bool,
	collapsed: propTypes.bool,
	searchFn: propTypes.func,
	resetFn: propTypes.func
};
